package io.mft.commons.db.mapper.proxyinvoker.invoker;

import java.lang.reflect.Method;

import cn.hutool.db.Entity;
import cn.hutool.db.Session;
import io.mft.commons.db.DbUtil;
import io.mft.commons.db.ISQLParameter;
import io.mft.commons.db.SQL;
import io.mft.commons.db.mapper.TbEntity;
import io.mft.commons.db.mapper.builder.ParameterWrapper;
import io.mft.commons.db.mapper.exception.MapperException;
import io.mft.commons.db.mapper.proxyinvoker.IProxyInvoker;
import io.mft.commons.db.mapper.proxyinvoker.invoker.sql.InvokerSQL;
import io.mft.commons.function.response.kv.KVMap;

public class TbDIUProxyInvoker implements IProxyInvoker<Integer> {

	@Override
	public Integer invoke(Method method, Session session, ISQLParameter sqlParameter, KVMap parameter,
			ParameterWrapper methodArgs) throws Exception {
		int i = 0;
		switch (methodArgs.getParameterMetadataWrapper().getTbDIUWraper().getDbOperateType()) {
		case jdbcDelete:
			if (methodArgs.getTbDIUWraper().getExpressionDbMapperParameter().size() == 0) {
				throw new MapperException("方法：" + method.getName() + "未设置数据库约束参数[ExpressionParam注解参数]");
			}
			KVMap p = new KVMap();
			p.set("tbName", methodArgs.getTbDIUWraper().getTbDIUMetadataWraper().getTbName());
			p.set("baseMapperParams", methodArgs.getTbDIUWraper().getExpressionDbMapperParameter());
			SQL sql = DbUtil.loadSQL(InvokerSQL.class, "deleteSQL", p);
			i = session.execute(sql.getSql(), sql.getArgs());
			break;
		case jdbcInsert:
			TbEntity tbEntity = methodArgs.getTbDIUWraper().getData();
			i = session.insert(tbEntity);
			break;
		case jdbcUpdate:
			if (methodArgs.getTbDIUWraper().getExpressionDbMapperParameter().size() == 0) {
				throw new MapperException("方法：" + method.getName() + "未设置数据库约束参数[ExpressionParam注解参数]");
			}
			i = update(session, methodArgs.getTbDIUWraper().getTbDIUMetadataWraper().getTbName(),
					methodArgs.getTbDIUWraper().getData(), methodArgs.getTbDIUWraper().getExpressionColumnArray(),
					methodArgs.getTbDIUWraper().getExpressionValueArray());
			break;
		default:
			break;
		}
		return i;
	}

	public int update(Session session, String tableName, Entity data, String[] identifys, Object[] identifyValues) {
		try {
			Entity where = new Entity();
			for (int i = 0; i < identifyValues.length; i++) {
				where.put(identifys[i], identifyValues[i]);
			}
			return session.update(data, where);
		} catch (Exception e) {
			throw new MapperException("", e);
		}
	}
}
